﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Eagles.Base;
using Eagles.Interface.Core.News;
using Eagles.Interface.Configuration;
using Eagles.Interface.DataAccess.Util;
using Eagles.Interface.DataAccess.NewsDa;
using Eagles.Interface.DataAccess.TaskAccess;
using Eagles.Interface.DataAccess.UserArticle;
using Eagles.Interface.DataAccess.ActivityAccess;
using Eagles.Application.Model;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.Common;
using Eagles.Application.Model.News.AddNewsViewCount;
using Eagles.Application.Model.News.EditUserNews;
using Eagles.Application.Model.News.GetNewsDetail;
using Eagles.Application.Model.News.GetModuleNews;
using Eagles.Application.Model.News.GetMeeting;
using Eagles.Application.Model.News.GetMeetingDetail;
using Eagles.Application.Model.News.GetUserNews;
using Eagles.Application.Model.News.GetUserNewsDetail;
using Eagles.Application.Model.News.GetPublicUserNews;
using Eagles.Application.Model.News.GetPublicUserNewsDetail;
using Eagles.Application.Model.News.GetUserRequisitionDetail;
using Eagles.DomainService.Model.Sms;
using Eagles.DomainService.Model.User;
using Eagles.Interface.DataAccess.SmsAccess;

namespace Eagles.DomainService.Core.News
{
    public class NewsHandler : INewsHandler
    {
        private readonly IArticleDataAccess articleData;
        private readonly INewsDa newsDa;
        private readonly IActivityAccess activityAccess;
        private readonly ITaskAccess taskAccess;
        private readonly IUtil util;
        private readonly IEaglesConfig configuration;
        private readonly ISmsAccess smsAccess;

        public NewsHandler(IArticleDataAccess articleData, INewsDa newsDa, IActivityAccess activityAccess,
            ITaskAccess taskAccess, IUtil util, IEaglesConfig configuration, ISmsAccess smsAccess)
        {
            this.articleData = articleData;
            this.newsDa = newsDa;
            this.activityAccess = activityAccess;
            this.taskAccess = taskAccess;
            this.util = util;
            this.configuration = configuration;
            this.smsAccess = smsAccess;
        }

        public EditUserNewsResponse EditUserNews(EditUserNewsRequest request)
        {
            var response = new EditUserNewsResponse();
            var toUserBranchId = 0; //介绍人支部
            var toUserPhone = "";
            var score = 0; //奖励积分
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var userInfo = util.GetUserInfo(tokens.UserId);
            if (userInfo == null)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            if (request.NewsType == NewsEnum.Requisition)
            {
                var toUser = util.GetUserInfo(request.ToUser);
                toUserBranchId = toUser.BranchId;
                toUserPhone = toUser.Phone;
            }
            var oriScore = userInfo.Score;
            var newsInfo = new TbUserNews()
            {
                NewsId = request.NewsId,
                OrgId = tokens.OrgId,
                BranchId = request.NewsType == NewsEnum.Requisition ? toUserBranchId : tokens.BranchId,
                UserId = tokens.UserId,
                ToUser = request.ToUser,
                Title = request.NewsTitle,
                HtmlContent = request.NewsContent,
                NewsType = request.NewsType,
                ImageUrl = request.ImageUrl,
                Status = request.IsPublic != 1 ? "0" : "-1", //发布文章，如果申请公开了 状态就不是 -1是0  如果不申请公开，就是-1
                CreateTime = DateTime.Now,
                RewardsScore = score,
                OrgReview = "-1",
                BranchReview = "-1",
                IsPublic = request.IsPublic,
                PublicTime = DateTime.Now,
                BookName = request.BookName,
                BookAuthor = request.BookAuthor
            };
            if (request.AttachList != null && request.AttachList.Count > 0)
            {
                var attachList = request.AttachList;
                for (int i = 0; i < attachList.Count; i++)
                {
                    switch (i)
                    {
                        case 0:
                            newsInfo.AttachName1 = attachList[i].AttachName;
                            newsInfo.Attach1 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 1:
                            newsInfo.AttachName2 = attachList[i].AttachName;
                            newsInfo.Attach2 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 2:
                            newsInfo.AttachName3 = attachList[i].AttachName;
                            newsInfo.Attach3 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 3:
                            newsInfo.AttachName4 = attachList[i].AttachName;
                            newsInfo.Attach4 = attachList[i].AttachmentDownloadUrl;
                            break;
                    }
                }
            }
            int result = 0;
            var resultNews = articleData.GetUserNewsDetail(request.NewsId, tokens.OrgId);
            if (resultNews == null)
            {
                //文章公开增加积分
                if (request.IsPublic == 2 || request.IsPublic == 3)
                {
                    //心得体会、会议流水
                    var scoreLs = new TbUserScoreTrace()
                    {
                        OrgId = tokens.OrgId,
                        UserId = tokens.UserId,
                        CreateTime = DateTime.Now
                    };
                    switch (request.NewsType)
                    {
                        case NewsEnum.Article: 
                            var articleReward = util.RewardScore(tokens.OrgId, "00"); //文章奖励
                            if (articleReward != null)
                            {
                                score = articleReward.Score;
                                var articleRewardLs = new TbUserScoreTrace()
                                {
                                    OrgId = tokens.OrgId,
                                    UserId = tokens.UserId,
                                    CreateTime = DateTime.Now,
                                    Score = articleReward.Score,
                                    RewardsType = "0",
                                    Comment = "文章发布奖励积分",
                                    OriScore = oriScore,
                                    Source = request.NewsTitle
                                };
                                oriScore += score;
                                if (score > 0)
                                {
                                    util.CreateScoreLs(articleRewardLs); //发布文章积分流水
                                }
                            }
                            var wordCountReward = util.RewardScore(tokens.OrgId, "01"); //文章字数奖励
                            if (wordCountReward != null && request.NewsContent.Length >= wordCountReward.WordCount)
                            {
                                score += wordCountReward.Score;
                                var wordCountLs = new TbUserScoreTrace()
                                {
                                    OrgId = tokens.OrgId,
                                    UserId = tokens.UserId,
                                    CreateTime = DateTime.Now,
                                    Score = wordCountReward.Score,
                                    RewardsType = "1",
                                    Comment = "文章发布字数奖励积分",
                                    OriScore = oriScore,
                                    Source = request.NewsTitle
                                };
                                oriScore += score;
                                if (score > 0)
                                {
                                    util.CreateScoreLs(wordCountLs); //文章发布字数积分流水
                                }
                            }

                            var keyWord = util.RewardScore(tokens.OrgId, "02"); //文章关键字奖励
                            if (keyWord != null)
                            {
                                var keyWordScore = 0;
                                var flag = false;
                                if (!string.IsNullOrWhiteSpace(keyWord.KeyWord))
                                {
                                    string[] keyWords = keyWord.KeyWord.Split(',');
                                    foreach (string key in keyWords)
                                    {
                                        if (request.NewsContent.IndexOf(key, StringComparison.Ordinal) >= 0)
                                        {
                                            flag = true;
                                            keyWordScore += keyWord.Score;
                                            continue;
                                        }
                                    }
                                }
                                if (flag)
                                {
                                    score += keyWordScore;
                                    var keyWordLs = new TbUserScoreTrace()
                                    {
                                        OrgId = tokens.OrgId,
                                        UserId = tokens.UserId,
                                        CreateTime = DateTime.Now,
                                        Score = keyWordScore,
                                        RewardsType = "2",
                                        Comment = "文章发布关键字奖励积分",
                                        OriScore = oriScore,
                                        Source = request.NewsTitle
                                    };
                                    if (score > 0)
                                    {
                                        util.CreateScoreLs(keyWordLs); //文章发布关键字积分流水
                                    }
                                }
                            }
                            break;
                        case NewsEnum.Meeting:
                            var meetReward = util.RewardScore(tokens.OrgId, "30"); //会议奖励
                            if (meetReward != null)
                            {
                                score = meetReward.Score;
                                scoreLs.Score = meetReward.Score;
                                scoreLs.RewardsType = "30";
                                scoreLs.Comment = "会议发布奖励积分";
                                scoreLs.OriScore = oriScore;
                                scoreLs.Source = request.NewsTitle;
                                if (score > 0)
                                {
                                    util.CreateScoreLs(scoreLs); //发布会议积分流水
                                }
                            }
                            break;
                        case NewsEnum.Experience:
                            var experience = util.RewardScore(tokens.OrgId, "40"); //心得体会奖励
                            if (experience != null)
                            {
                                score = experience.Score;
                                scoreLs.Score = experience.Score;
                                scoreLs.RewardsType = "40";
                                scoreLs.Comment = "心得体会发布奖励积分";
                                scoreLs.OriScore = oriScore;
                                scoreLs.Source = request.NewsTitle;
                                if (score > 0)
                                {
                                    util.CreateScoreLs(scoreLs); //发布心得体会积分流水
                                }
                            }
                            break;
                    }
                    if (score > 0)
                    {
                        util.EditUserScore(tokens.UserId, score); //用户增加积分
                    }
                }
                result = articleData.CreateArticle(newsInfo); //新增
                if (result >= 0 && request.NewsType == NewsEnum.Requisition && request.IsPublic != 1)
                {
                    //todo 发短信

                    //生成验证码
                    var rd = new Random();
                    var seq = rd.Next(10, 99);
                    var code = rd.Next(1000, 9999);
                    var smsConfig = smsAccess.GetSmsConfig(request.AppId);
                    if (smsConfig == null)
                        throw new TransactionException(MessageCode.ConfigNotExists, MessageKey.ConfigNotExists);
                    var sendCount = smsConfig.SendCount;
                    var maxCount = smsConfig.MaxCount;
                    if (sendCount >= maxCount)
                        throw new TransactionException(MessageCode.SendSmsMax, MessageKey.SendSmsMax);
                    var smsSendLogLog = new TbSmsSendLog()
                    {
                        OrgId = request.AppId,
                        VendorId = smsConfig.VendorId,
                        CreateTime = DateTime.Now,
                        Phone = toUserPhone
                    };
                    if (smsConfig.VendorId == configuration.EaglesConfiguration.AliyunVendorId)
                    {
                        #region 阿里云

                        //阿里云
                        var product = "Dysmsapi"; //短信API产品名称
                        var domain = "dysmsapi.aliyuncs.com"; //短信API产品域名
                        var accessKeyId = smsConfig.SginKey;
                        var accessKeySecret = smsConfig.AppKey;
                        var regionIdForPop = "cn-hangzhou";
                        IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessKeyId, accessKeySecret);
                        DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
                        IAcsClient acsClient = new DefaultAcsClient(profile);
                        SendSmsRequest sendSmsrequest = new SendSmsRequest();
                        try
                        {
                            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                            sendSmsrequest.PhoneNumbers = toUserPhone;
                            //必填:短信签名-可在短信控制台中找到
                            sendSmsrequest.SignName = configuration.EaglesConfiguration.AliyunSignName;
                            //必填:短信模板-可在短信控制台中找到
                            sendSmsrequest.TemplateCode = configuration.EaglesConfiguration.AliyunReferrerTemplateCode;
                            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                            var template = "{\"code\":\"" + code + "\"}";
                            sendSmsrequest.TemplateParam = template;
                            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                            //sendSmsrequest.OutId = "21212121211";
                            //请求失败这里会抛ClientException异常

                            var requestMsg = new StringBuilder();
                            foreach (var parameters in sendSmsrequest.QueryParameters)
                                requestMsg.AppendFormat("{0}:{1},", parameters.Key, parameters.Value);
                            requestMsg.Remove(requestMsg.ToString().LastIndexOf(','), 1);
                            smsSendLogLog.RequestMsg = requestMsg.ToString();

                            SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(sendSmsrequest);
                            if (sendSmsResponse.Code == "OK")
                                smsSendLogLog.Status = 0;
                            else
                                smsSendLogLog.Status = 1;
                            smsSendLogLog.SmsContent = template;
                            smsSendLogLog.ResponseMsg = sendSmsResponse.Message;
                        }
                        catch (ServerException e)
                        {
                            smsSendLogLog.ResponseMsg = "ServerException" + e.ErrorCode + e.ErrorMessage;
                        }
                        catch (ClientException e)
                        {
                            smsSendLogLog.ResponseMsg = "ClientException" + e.ErrorCode + e.ErrorMessage;
                        }

                        #endregion
                    }
                    else if (smsConfig.VendorId == configuration.EaglesConfiguration.BaiduVendorId)
                    {
                        //百度云
                    }
                    else if (smsConfig.VendorId == configuration.EaglesConfiguration.TencentVendorId)
                    {
                        //腾讯云
                    }
                    else
                    {
                        throw new TransactionException(MessageCode.ConfigNotExists, MessageKey.ConfigNotExists);
                    }
                    smsAccess.CreateSmsSendLog(smsSendLogLog); //记录短信日志
                    smsAccess.AddSendCount(request.AppId, smsConfig.VendorId); //短信数量+1
                    
                }
            }
            else
            {
                //文章状态只有在
                if (resultNews.Status != "-1")
                    throw new TransactionException(MessageCode.ArticleStatusError, MessageKey.ArticleStatusError);
                result = articleData.EditArticle(newsInfo); //修改
            }
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }
        
        public AddNewsViewCountResponse AddNewsViewCount(AddNewsCountRequest request)
        {
            if (request.NewsId < 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = newsDa.AddNewsViewCount(request.Type, request.NewsId);
            return new AddNewsViewCountResponse();
        }

        public GetUserNewsResponse GetUserNews(GetUserNewsRequest request)
        {
            var response = new GetUserNewsResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var news = articleData.GetUserNews(request.NewsType, tokens.UserId, request.PageIndex, request.PageSize);
            if (news != null && news.Count > 0)
            {
                response.NewsList = news.Select(x => new UserNews
                {
                    NewsId = x.NewsId,
                    Title = x.Title,
                    NewsContent = x.HtmlContent,
                    NewsType = x.NewsType,
                    ToUser = x.ToUser,
                    CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                    ViewsCount = x.ViewsCount,
                    ImageUrl = x.ImageUrl,
                    Status = x.Status
                }).ToList();
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetUserNewsDetailResponse GetUserNewsDetail(GetUserNewsDetailRequest request)
        {
            var response = new GetUserNewsDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var news = articleData.GetUserNewsDetail(request.NewsId, request.AppId);
            if (news != null)
            {
                response.NewsId = news.NewsId;
                response.NewsType = news.NewsType;
                response.UserName = news.Name;
                response.Title = news.Title;
                response.HtmlContent = news.HtmlContent;
                response.ImageUrl = news.ImageUrl;
                response.Status = news.Status;
                response.IsPublic = news.IsPublic;
                response.ToUserId = news.ToUser;
                response.Introducer = news.Introducer;
                response.BookName = news.BookName;
                response.BookAuthor = news.BookAuthor;
                response.UserId = news.UserId;
                response.LikeCount = news.LikeCount;
                response.FavoritesCount = news.FavoritesCount;
                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = news.AttachName1, AttachmentDownloadUrl = news.Attach1},
                    new Attachment() {AttachName = news.AttachName2, AttachmentDownloadUrl = news.Attach2},
                    new Attachment() {AttachName = news.AttachName3, AttachmentDownloadUrl = news.Attach3},
                    new Attachment() {AttachName = news.AttachName4, AttachmentDownloadUrl = news.Attach4}
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetPublicUserNewsResponse GetPublicUserNews(GetPublicUserNewsRequest request)
        {
            var response = new GetPublicUserNewsResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var token = request.Token;
            var tokens = util.GetUserId(request.Token, 0);
            var branchId = 0;
            if (tokens != null && tokens.UserId > 0)
            {
                branchId = tokens.BranchId;
            }
            var news = articleData.GetPblicUserNews(request.AppId, branchId, false, request.PageIndex, request.PageSize);
            if (news != null && news.Count > 0)
            {
                response.NewsList = news.Select(x => new UserNews
                {
                    NewsId = x.NewsId,
                    Title = x.Title,
                    NewsContent = x.HtmlContent,
                    NewsType = x.NewsType,
                    CreateTime = x.CreateTime.ToString("yyyy-MM-dd"),
                    ViewsCount = x.ViewsCount,
                    ImageUrl = x.ImageUrl
                }).ToList();
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetPublicUserNewsDetailResponse GetPublicUserNewsDetail(GetPublicUserNewsDetailRequest request)
        {
            var response = new GetPublicUserNewsDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var news = articleData.GetPublicUserNewsDetail(request.NewsId, request.AppId);
            if (news != null)
            {
                response.NewsId = news.NewsId;
                response.NewsType = news.NewsType;
                response.UserName = news.Name;
                response.Title = news.Title;
                response.HtmlContent = news.HtmlContent;
                response.ImageUrl = news.ImageUrl;
                response.ViewCount = news.ViewCount;
                response.UserId = news.UserId;
                response.BookAuthor = news.BookAuthor;
                response.BookName = news.BookName;
                response.LikeCount = news.LikeCount;
                response.FavoritesCount = news.FavoritesCount;
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetModuleNewsResponse GetModuleNews(GetModuleNewsRequest request)
        {
            var response = new GetModuleNewsResponse();
            var view = 0;
            if (request.ModuleId < 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var module = newsDa.GetSubCateType(request.ModuleId, request.AppId);
            if (request.NewsCount > 0)
                view = request.NewsCount;
            else
                view = request.PageSize;
            var tokens = util.GetUserId(request.Token, 0);
            var branchId = 0;
            if (tokens != null && tokens.UserId > 0)
                branchId = tokens.BranchId;
            switch (module.SubCateType)
            {
                case SubCateEnum.Default:
                    var result = newsDa.GetModuleNews(request.ModuleId, request.AppId, request.IsHome, request.PageIndex, view, branchId);
                    if (result != null && result.Count > 0)
                    {
                        response.NewsInfos = result?.Select(x => new Application.Model.Common.News
                        {
                            NewsId = x.NewsId,
                            Title = x.Title,
                            NewsContent = x.ShortDesc,
                            CreateTime = x.CreateTime.ToString("yyyy-MM-dd"),
                            Author = x.Author,
                            Source = x.Source,
                            ImageUrl = x.ImageUrl,
                            IsVideo = x.IsVideo,
                            IsExternal = x.IsExternal == 1,
                            ExternalUrl = x.ExternalUrl
                        }).ToList();
                    }
                    else
                        throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                    break;
                case SubCateEnum.ActivityPublic:
                    var activity = activityAccess.GetPublicActivity(request.AppId, request.IsHome, branchId, request.PageIndex, view);
                    if (activity != null && activity.Count > 0)
                    {
                        response.NewsInfos = activity.Select(x => new Application.Model.Common.News
                        {
                            NewsId = x.ActivityId,
                            Title = x.ActivityName,
                            NewsContent = x.HtmlContent,
                            CreateTime = x.BeginTime.ToString("yyyy-MM-dd"),
                            Author = x.FromUserName,
                            Source = x.BranchName,
                            ImageUrl = x.ImageUrl,
                            IsExternal = true,
                            ExternalUrl = string.Format(configuration.EaglesConfiguration.PublicActivityUrl, x.OrgId, x.ActivityId)
                        }).ToList();
                    }
                    else
                        throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                    break;
                case SubCateEnum.TaskPublic:
                    var task = taskAccess.GetPublicTask(request.AppId, branchId, request.PageIndex, view);
                    if (task != null && task.Count > 0)
                    {
                        response.NewsInfos = task.Select(x => new Application.Model.Common.News
                        {
                            NewsId = x.TaskId,
                            Title = x.TaskName,
                            NewsContent = x.TaskContent,
                            CreateTime = x.BeginTime.ToString("yyyy-MM-dd"),
                            Author = x.FromUserName,
                            Source = x.BranchName,
                            ImageUrl = configuration.EaglesConfiguration.PublicTaskDefaultImg,
                            IsExternal = true,
                            ExternalUrl = string.Format(configuration.EaglesConfiguration.PublicTaskUrl, x.OrgId, x.TaskId)
                        }).ToList();
                    }
                    else
                        throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                    break;
                case SubCateEnum.ArticlePublic:
                    var news = articleData.GetPblicUserNews(request.AppId, branchId, request.IsHome, request.PageIndex, view);
                    if (news != null && news.Count > 0)
                    {
                        response.NewsInfos = news.Select(x => new Application.Model.Common.News
                        {
                            NewsId = x.NewsId,
                            Title = x.Title,
                            NewsContent = x.HtmlContent,
                            CreateTime = x.CreateTime.ToString("yyyy-MM-dd"),
                            Author = x.Name,
                            Source = x.BranchName,
                            ImageUrl = x.ImageUrl,
                            IsExternal = true,
                            ExternalUrl = string.Format(configuration.EaglesConfiguration.PublicArticleUrl, x.OrgId, x.NewsId)
                        }).ToList();
                    }
                    else
                        throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                    break;
            }
            return response;
        }

        public GetNewsDetailResponse GetNewsDetail(GetNewsDetailRequest request)
        {
            var response = new GetNewsDetailResponse();
            if (request.NewsId < 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = newsDa.GetNewsDetail(request.NewsId, request.AppId);
            if (result != null)
            {
                response.NewsId = result.NewsId;
                response.ShortDesc = result.ShortDesc;
                response.Title = result.Title;
                response.HtmlContent = result.HtmlContent;
                response.Author = result.Author;
                response.Source = result.Source;
                response.Module = result.Module;
                response.ViewCount = result.ViewCount;
                response.CreateTime = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.TestId = result.TestId;
                response.IsAttach = result.IsAttach;
                response.Attach = new List<Attachment>
                {
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach1,
                        AttachName = result.AttachName1
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach2,
                        AttachName = result.AttachName2
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach3,
                        AttachName = result.AttachName3
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach4,
                        AttachName = result.AttachName4
                    },
                };
                response.ViewCount = result.ViewCount;
                response.CanStudy = result.CanStudy;
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }
        
        public GetMeetingResponse GetMeeting(GetMeetingRequest request)
        {
            var response = new GetMeetingResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var news = newsDa.GetMeetings(request.MeetType, tokens.UserId, tokens.OrgId, request.PageIndex, request.PageSize);
            var meetingCount = newsDa.GetMeetingsCount(request.MeetType, tokens.UserId, tokens.OrgId);
            response.MeetingCount = meetingCount;
            if (news != null && news.Count > 0)
            {
                response.MeetingList = news.Select(x => new Meeting
                {
                    NewsId = x.NewsId,
                    Title = x.Title,
                    CreateTime = x.CreateTime.ToString("yyyy-MM-dd"),
                    ImageUrl = x.ImageUrl
                }).ToList();
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetMeetingDetailResponse GetMeetingDetail(GetMeetingDetailRequest request)
        {
            var response = new GetMeetingDetailResponse();
            if (request.NewsId < 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = newsDa.GetMeetingDetail(request.NewsId, request.AppId);
            if (result != null)
            {
                response.NewsId = result.NewsId;
                response.Title = result.Title;
                response.HtmlContent = result.HtmlContent;
                response.Author = result.Author;
                response.CreateTime = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.MeetingJoinPeopleList = newsDa.GetMeetingJoinPeople(request.NewsId);
                response.Attach = new List<Attachment>
                {
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach1,
                        AttachName = result.AttachName1
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach2,
                        AttachName = result.AttachName2
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach3,
                        AttachName = result.AttachName3
                    },
                    new Attachment()
                    {
                        AttachmentDownloadUrl = result.Attach4,
                        AttachName = result.AttachName4
                    },
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetUserRequisitionDetailResponse GetUserRequisitionDetail(GetUserRequisitionDetailRequest request)
        {
            var response = new GetUserRequisitionDetailResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var news = articleData.GetUserRequisitionDetail(request.AppId, tokens.UserId);
            if (news != null)
            {
                response.NewsId = news.NewsId;
                response.NewsType = news.NewsType;
                response.UserName = news.Name;
                response.Title = news.Title;
                response.HtmlContent = news.HtmlContent;
                response.ImageUrl = news.ImageUrl;
                response.Status = news.Status;
                response.IsPublic = news.IsPublic;
                response.ToUserId = news.ToUser;
                response.Introducer = news.Introducer;
                response.BookName = news.BookName;
                response.BookAuthor = news.BookAuthor;
                response.UserId = news.UserId;
                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = news.AttachName1, AttachmentDownloadUrl = news.Attach1},
                    new Attachment() {AttachName = news.AttachName2, AttachmentDownloadUrl = news.Attach2},
                    new Attachment() {AttachName = news.AttachName3, AttachmentDownloadUrl = news.Attach3},
                    new Attachment() {AttachName = news.AttachName4, AttachmentDownloadUrl = news.Attach4}
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }
    }
}